package cfs.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import cfs.databean.Customer;
import cfs.model.CustomerDAO;
import cfs.model.Model;

/**
 * Servlet implementation class ChangePassword
 */
public class ResetPasswordAction extends Action {
//	private EmployerDAO employeeDAO;
	private CustomerDAO userDAO;
	private EmailService emailS;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ResetPasswordAction(Model model) {
		super();
		userDAO = model.getCustomerDao();
		emailS = new EmailService(model);
		// TODO Auto-generated constructor stub
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "resetPassword.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		try {
			// PasswordFormBean form = formBeanFactory.create(request);
			// request.setAttribute("form", form);

			// if (!form.isPresent()) {
			// return "viewAllCustomerList.jsp";
			// }

			// errors.addAll(form.getValidationErrors());
			// if (errors.size() != 0) {
			// return "viewAllCustomerList.jsp";
			// }

			// HttpSession session = request.getSession();
			String userInput = (String) request.getParameter("selectedUser");
			System.out.println("userINput: " + userInput);
			int userID = Integer.parseInt(userInput);
			// if (session.getAttribute("employee") == null) {
			// errors.add("You cannot go to this page");
			// return "viewAllCustomerList.jsp";
			// }

			String newPassword = "";
			if (userID > 0) {
				Customer user = null;
				user = userDAO.lookup(userID);
				if (user != null) {
					newPassword = generateNewPassword(user);
					user.setPassword(newPassword);
					userDAO.update(user);
				}
				// TODO: call my email service class;
				emailS.activeEmailService(1, user);// pass in the customer
													// object and call method 2
			}


			request.setAttribute("successStatement", "Password has been reset");
			return "Success.jsp";
		} catch (Exception e) {
			errors.add("There is an error");
			return "Success.jsp";
		}
	}

	private String generateNewPassword(Customer currentEmp) {
		String generatedString = "";
		int value = (int) (Math.random() * 1000000);
		generatedString = currentEmp.getLastname() + value;
		return generatedString;
	}

}
